import { Component, Input, Output, EventEmitter, ViewChild, OnDestroy, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { DepartService } from '../../../service/depart/depart.service';
import { NzTreeComponent, NzModalRef, NzMessageService, NzTreeNode, NzFormatEmitEvent } from 'ng-zorro-antd';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { Subject, Observable } from 'rxjs';
declare var _: any;

@Component({
    selector: 'depart-select',
    templateUrl: './departs-modal.component.html'
})
export class DepartsModalComponent implements OnInit {    
    @Output() departs: any;
    defaultCheckList = [];
    @ViewChild('nzTree') nzTree: NzTreeComponent;
    private subject = new Subject();
    
    constructor(
        private modal: NzModalRef,        
        public msg: NzMessageService, 
        private modalSrv: ModalHelper,
        private departService: DepartService,                
        private http: _HttpClient
    ) {        
        
    }

    ngOnInit() {
        this.loadDepart();        
    }

    loadDepart() {
        // 获取所有的门店信息
        this.departService.departTree().subscribe(data => {
            this.departs = [];
            let o = this.replaceKeysDeep(data, this.mapShortToLong);
            
            for (let index = 0; index < o.length; index++) {
                this.departs.push(
                    new NzTreeNode(o[index])
                );
            }                 
        });
    }

    mapShortToLong: any = {
        "id": "key",
        "label": "title"
    };

    replaceKeysDeep(obj, keysMap) { // keysMap = { oldKey1: newKey1, oldKey2: newKey2, etc...
        let that = this;
        return _.transform(obj, function(result, value, key) { // transform to a new object
      
          var currentKey = keysMap[key] || key; // if the key is in keysMap use the replacement, if not use the original key
      
          result[currentKey] = _.isObject(value) ? that.replaceKeysDeep(value, keysMap) : value; // if the key is an object run it through the inner function - replaceKeys
        });
    }

    close() {
        this.modal.close(true);
        this.modal.destroy();
    }

    mouseAction(name: string, e: NzFormatEmitEvent): void {        
    }

    save() {
        const list:NzTreeNode[] = this.nzTree.getSelectedNodeList();
        if (list.length == 0) {
            this.msg.warning('请选择部门');
            return;
        }        
        this.subject.next(list[0]);
        this.close();        
    }

    getSubject() {
        return this.subject;
    }
}